package com.emode.service.impl;

import org.apache.log4j.Logger;
import org.json.JSONException;

import com.emode.base.BaseDaoImpl;
import com.emode.entity.Upfile;
import com.emode.qiniu.api.QiniuConst;
import com.emode.service.FilesService;
import com.emode.util.FileUtil;
import com.emode.util.StringUtils;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;

public class FileServiceImpl extends BaseDaoImpl<Upfile> implements FilesService {
	private Logger logger = Logger.getLogger(FileServiceImpl.class);
	@Override
	public void upload(final String key, final String filePath) {
		System.out.println(FileUtil.isFile(filePath)&&!StringUtils.isBlank(key));
		if(FileUtil.isFile(filePath)&&!StringUtils.isBlank(key)){
			new Thread() {
				public void run() {
					PutPolicy putPolicy = new PutPolicy(QiniuConst.BUCKETNAME);
					Mac mac = new Mac(QiniuConst.ACCESS_KEY, QiniuConst.SECRET_KEY);
					String uptoken;
					try {
						uptoken = putPolicy.token(mac);
						PutExtra extra = new PutExtra();
						PutRet ret = IoApi.putFile(uptoken, key, filePath, extra);
						System.out.println(ret);
						System.out.println(key + "上传结果：" + ret.getResponse());
						logger.info(key + "上传结果：" + ret.getResponse());
					} catch (AuthException e) {
						e.printStackTrace();
					} catch (JSONException e) {
						e.printStackTrace();
					}
				};
			}.start();
		}
		
	}

}
